#!/usr/bin/env python

from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By 
from selenium.common.exceptions import StaleElementReferenceException, NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys


import tkinter as tk
from tkinter import Label, Entry, Button, messagebox, END

import constant
import time
from functools import partial



# import sys
# import io
# sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')


def do_login(dri, user_val, pawd_val):
    sub_content1_item = dri.find_element(By.XPATH, "//*[@class='sub-content1']").\
                            find_elements(By.XPATH, "//*[@class='form-body']")[1].\
                            find_elements(By.XPATH, "//*[@class='form-item']")[2]

    usern = sub_content1_item.find_element(By.NAME, 'username')
    passw = sub_content1_item.find_element(By.NAME, 'password')
    login = sub_content1_item.find_elements(By.XPATH, "//*[@class='btn btn-block login-btn']")[2]

    usern.send_keys(user_val)
    passw.send_keys(pawd_val)
    login.click()


def enter_learning(dri):
    learn1 = dri.find_element(By.XPATH, "//*[@class='redbtn']")
    learn1.click()
    time.sleep(3)

    learn2 = dri.find_element(By.XPATH, "//*[@class='button intoStudy']")
    learn2.click()
    time.sleep(3)

    windows = dri.window_handles
    dri.switch_to.window(windows[-1])

    learn3 = dri.find_element(By.XPATH, "//*[@class='btnBig2']")
    learn3.click()


def check_paused(dri):
    try:            
        ele = dri.find_element(By.XPATH, "//*[@class='dialog-table']").\
                    find_element(By.XPATH, "//*[@class='dialog-button-container']").\
                    find_element(By.TAG_NAME, "button")
        ele.click()
    except NoSuchElementException:
        pass
    except Exception:
        print('...')


def check_ended(dri):
    try:
        progress_eles = dri.find_elements(By.XPATH, "//*[@class='cvtb-MCK-CsCt-studyProgress']")
        for ele in progress_eles:
            if ele.text != "100%":
                return ele.text
        return "100%"
    except:
        return False


def play_video(dri):
    while True:
        check_paused(dri)
        progress_text = check_ended(dri)
        if progress_text == "100%":
            break
        else:
            time.sleep(10)


def list_learnings_and_play_all(dri):
    trs = dri.find_element(By.XPATH, "//*[@id='J_listContent']").\
                find_elements(By.TAG_NAME, 'tr')
    trs_len = len(trs)
    for i in range(trs_len):    
        tds = trs[i].find_elements(By.TAG_NAME, "td")
        if len(tds) != constant.LEARNING_COLUMN_LENGTH:
            continue
        if tds[4].text == "100%":
            continue        

        ActionChains(dri).send_keys(Keys.END).perform()
        time.sleep(1)
        tds[5].click()
        time.sleep(3)
        windows = dri.window_handles
        dri.switch_to.window(windows[-1])

        # for-loop video over
        time.sleep(3)
        play_video(dri)
        dri.close()
        dri.switch_to.window(windows[1])


def play_all(user_val, pawd_val):
    dri = Chrome()
    dri.maximize_window()
    dri.get(constant.XXGS_URL_HOMEPAGE)
    time.sleep(3)

    do_login(dri, user_val, pawd_val)
    time.sleep(3)
    
    enter_learning(dri)
    time.sleep(3)

    list_learnings_and_play_all(dri)
    time.sleep(3)

    dri.quit()


if __name__ == '__main__':
    window = tk.Tk()
    window.title('学习公社学习助手')

    login_use_tip=Label(window, text='用户名',font=('宋体',15), fg='black')
    login_use_tip.grid()

    login_user = Entry(window, font=('宋体', 14), fg='black')
    login_user.grid(row=0,column=1)

    login_pawd_tip = Label(window, text='密码', font=('宋体',15), fg='black')
    login_pawd_tip.grid()

    login_pawd = Entry(window, font=('宋体', 14), fg='black')
    login_pawd.grid(row=1,column=1)

    def callback(login_user, login_pawd):
        user_val,  pass_val = login_user.get(), login_pawd.get()
        messagebox.showinfo(title='学习公社学习助手', message='开始播放视频')
        login_user.delete(0, END)
        login_pawd.delete(0, END)
        play_all(user_val, pass_val)


    button = Button(window, text='确认学习',font=('宋体',14), fg='black', \
                    command=partial(callback, login_user, login_pawd))
    button.grid(row=2, column=1)

    window.geometry('600x450+374+120')
    window.mainloop()
